import axios from "axios"
import { message } from "ant-design-vue"

const baseUrl =
	window.parent.APP_CONFIG?.baseURL || process.env.VUE_APP_API_BASE_URL
// localStorage.getItem('Access-Token') || localStorage.setItem('Access-Token', '')
const instance = axios.create({
	baseURL: baseUrl,
	headers: {
		"Content-Type": "application/json;charset=UTF-8",
		Authorization:
			window.parent.APP_CONFIG?.token ||
			localStorage.getItem("Access-Token"),
	},
})

instance.interceptors.request.use(
	(config) => {
		return config
	},
	(err) => Promise.reject(err)
)
instance.interceptors.response.use(
	(response) => {
		if (response.config.pass) {
			return Promise.resolve(response.data)
		}
		if (response.status === 200) {
			if (response.data.code === 0) {
				return Promise.resolve(response.data.data)
			} else if (response.data.code == 2004) {
				// 401
				relogin(response.data.message)
			} else {
				if (!response.config.hideErr) {
					onError(response.data.message)
				}
				return Promise.reject(response.data)
			}
		}
		onError(response.data.message)
		return Promise.resolve(response)
	},
	(error) => {
		const msg =
			(error.response &&
				error.response &&
				error.response.data &&
				error.response.data.message) ||
			error.message
		onError(msg)
		return Promise.reject(error)
	}
)

function onError(content) {
	message.error({ content, key: "onError", duration: 3 })
}
function relogin(content) {
	message.warning({ content, key: "relogin", duration: 3 })
}

const request = {
	get(url, params) {
		return instance({
			method: "get",
			url,
			params,
		})
	},
	post(url, data, config) {
		return instance({
			method: "post",
			url,
			data,
			...config,
		})
	},
	put(url, data, config) {
		return instance({
			method: "put",
			url: url,
			data,
			...config,
		})
	},
	delete(url, data) {
		return instance({
			method: "delete",
			url: url,
			data,
			headers: {
				"Content-Type": "application/x-www-form-urlencoded",
			},
		})
	},
}
export default request
